<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-row :gutter="20">
        <!-- 用户统计 -->
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <div class="stat-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-title">用户统计</div>
            </div>
            <div class="stat-content">
              <div class="stat-item">
                <div class="label">学生数量</div>
                <div class="value">{{ stats.totalStudents }}</div>
              </div>
              <div class="stat-item">
                <div class="label">教师数量</div>
                <div class="value">{{ stats.totalTeachers }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 岗位统计 -->
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <div class="stat-icon">
                <el-icon><Briefcase /></el-icon>
              </div>
              <div class="stat-title">岗位统计</div>
            </div>
            <div class="stat-content">
              <div class="stat-item">
                <div class="label">总岗位数</div>
                <div class="value">{{ stats.totalPositions }}</div>
              </div>
              <div class="stat-item">
                <div class="label">开放岗位</div>
                <div class="value">{{ stats.openPositions }}</div>
              </div>
              <div class="stat-item">
                <div class="label">申请数量</div>
                <div class="value">{{ stats.totalApplications }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 奖学金统计 -->
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <div class="stat-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-title">奖学金统计</div>
            </div>
            <div class="stat-content">
              <div class="stat-item">
                <div class="label">奖学金项目</div>
                <div class="value">{{ stats.totalScholarships }}</div>
              </div>
              <div class="stat-item">
                <div class="label">申请数量</div>
                <div class="value">{{ stats.totalScholarshipApplications }}</div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 反馈统计 -->
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-header">
              <div class="stat-icon">
                <el-icon><Message /></el-icon>
              </div>
              <div class="stat-title">反馈统计</div>
            </div>
            <div class="stat-content">
              <div class="stat-item">
                <div class="label">总反馈数</div>
                <div class="value">{{ stats.totalFeedbacks }}</div>
              </div>
              <div class="stat-item">
                <div class="label">待处理</div>
                <div class="value">{{ stats.pendingFeedbacks }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts">
      <el-row :gutter="20">
        <!-- 岗位分布图 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <div class="chart-header">
              <div class="chart-title">岗位分布</div>
            </div>
            <div class="chart-content">
              <div ref="positionChartRef" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>

        <!-- 申请趋势图 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <div class="chart-header">
              <div class="chart-title">申请趋势</div>
            </div>
            <div class="chart-content">
              <div ref="applicationChartRef" style="height: 300px"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AdminDashboard'
}
</script>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Briefcase, Money, Message } from '@element-plus/icons-vue'
import { getDashboardStats } from '@/api/admin/dashboard'
import * as echarts from 'echarts'

// 初始化数据结构
const stats = ref({
  totalStudents: 0,
  totalTeachers: 0,
  totalPositions: 0,
  openPositions: 0,
  totalApplications: 0,
  totalScholarships: 0,
  totalScholarshipApplications: 0,
  totalFeedbacks: 0,
  pendingFeedbacks: 0,
  months: [],
  jobTrends: [],
  scholarshipTrends: []
})

const positionChartRef = ref(null)
const applicationChartRef = ref(null)
let positionChart = null
let applicationChart = null
const loading = ref(false)

// 获取统计数据
const fetchStats = async () => {
  try {
    loading.value = true
    const response = await getDashboardStats()
    console.log('Response data:', response) // 添加日志
    Object.assign(stats.value, response)
    console.log('Updated stats:', stats.value) // 添加日志
  } catch (error) {
    console.error('Failed to fetch stats:', error)
    ElMessage.error(error.response || '获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化岗位分布图
const initPositionChart = () => {
  if (!positionChartRef.value) {
    console.warn('Position chart ref not found') // 添加日志
    return
  }
  
  try {
    if (positionChart) {
      positionChart.dispose()
    }
    
    positionChart = echarts.init(positionChartRef.value)
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: [
            { value: stats.value.openPositions, name: '开放岗位' },
            { 
              value: stats.value.totalPositions - stats.value.openPositions, 
              name: '已关闭岗位' 
            }
          ]
        }
      ]
    }
    positionChart.setOption(option)
  } catch (error) {
    console.error('Failed to init position chart:', error) // 添加日志
  }
}

// 初始化申请趋势图
const initApplicationChart = () => {
  if (!applicationChartRef.value) {
    console.warn('Application chart ref not found')
    return
  }
  
  try {
    if (applicationChart) {
      applicationChart.dispose()
    }
    
    applicationChart = echarts.init(applicationChartRef.value)
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['岗位申请', '奖学金申请']
      },
      xAxis: {
        type: 'category',
        data: stats.value.months || []
      },
      yAxis: {
        type: 'value',
        name: '申请数量'
      },
      series: [
        {
          name: '岗位申请',
          type: 'line',
          smooth: true,
          data: stats.value.jobTrends || []
        },
        {
          name: '奖学金申请',
          type: 'line',
          smooth: true,
          data: stats.value.scholarshipTrends || []
        }
      ]
    }
    applicationChart.setOption(option)
  } catch (error) {
    console.error('Failed to init application chart:', error)
  }
}

// 监听窗口大小变化
const handleResize = () => {
  positionChart?.resize()
  applicationChart?.resize()
}

// 组件挂载时初始化
onMounted(async () => {
  console.log('Component mounted') // 添加日志
  await fetchStats()
  console.log('Stats fetched:', stats.value) // 添加日志
  initPositionChart()
  initApplicationChart()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  positionChart?.dispose()
  applicationChart?.dispose()
})

// 监听数据变化
watch(stats, (newVal) => {
  console.log('Stats changed:', newVal) // 添加日志
  initPositionChart()
  initApplicationChart()
}, { deep: true })
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
  .stat-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    
    .stat-icon {
      font-size: 24px;
      margin-right: 10px;
      color: #409EFF;
    }
    
    .stat-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .stat-content {
    .stat-item {
      margin-bottom: 10px;
      
      .label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }
      
      .value {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
}

.charts {
  margin-top: 20px;
}

.chart-card {
  .chart-header {
    margin-bottom: 20px;
    
    .chart-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .chart-content {
    height: 300px;
  }
}

/* 卡片hover效果 */
.el-card {
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  }
}
</style> 